// 使用 CSR 来编写
import { useEffect } from 'react';
import { Form, Input, Button, message } from 'antd';

import requestInstance from '@/service/fetch';

import styles from './index.module.scss';
import { useRouter } from 'next/router';

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 4 },
};

const UserProfile = () => {
  const [form] = Form.useForm();
  const { push } = useRouter()

  useEffect(() => {
    getData()
  }, [form])

  const getData = async () => {
    const result: any = await requestInstance.get('api/user/detail');
    if (result.code === 200) {
      form.setFieldsValue(result.data)
    }
  }

  const handleSubmit = async (values: any) => {
    const result: any = await requestInstance.post('api/user/update', {
      ...values
    })

    if (result.code === 200) {
      push(`/user/${result.data.id}`)
      message.success('更新成功')
    } else {
      message.error('更新失败')
    }
  }

  return (
    <div className="content-layout">
      <div className={styles.userProfile}>
        <h2>个人资料</h2>
        <div>
          <Form
            {...layout}
            form={form}
            className={styles.form}
            onFinish={handleSubmit}
          >
            <Form.Item label="用户名" name="nickname">
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item label="职位" name="job">
              <Input placeholder="请输入职位" />
            </Form.Item>
            <Form.Item label="个人介绍" name="introduction">
              <Input placeholder="请输入个人介绍" />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                保存修改
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default UserProfile;
